<template>
    <view class="tabs">
        <scroll-view id="tab-bar" class="scroll-h" :scroll-x="true" :show-scrollbar="false" :scroll-into-view="scrollInto">
            <view v-for="(tab,index) in tabBars" :key="tab.index" class="uni-tab-item"  :data-current="index" @click="ontabtap">
                <text class="uni-tab-item-title" :class="tabIndex==index ? 'uni-tab-item-title-active' : ''">{{tab.name}}</text>
            </view>
        </scroll-view>
        <view class="line-h"></view>
        <swiper :current="tabIndex" class="swiper-box" style="flex: 1;" :duration="300">
            <swiper-item class="swiper-item" v-for="(tab,index1) in newsList" :key="index1">
			
				<!-- #ifndef APP-NVUE -->
				<scroll-view class="scroll-v list" enableBackToTop="true" scroll-y @scrolltolower="loadMore(index1)">
					<view v-for="(newsitem,index2) in tab.data" :key="newsitem.index2">
						<media-item :options="newsitem"></media-item>
					</view>
					<view class="loading-more" v-if="tab.isLoading || tab.data.length > 4">
						<text class="loading-more-text">{{tab.loadingText}}</text>
					</view>
				</scroll-view>
				<!-- #endif -->
            </swiper-item>
        </swiper>
		
		<view class="cu-load load-modal" v-if="isLoading">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<view class="gray-text">{{loadMoreDefalutText}}</view>
		</view>
    </view>
</template>
<script>
    import mediaItem from './news-item.nvue';

    // 缓存每页最多
    const MAX_CACHE_DATA = 100;
    // 缓存页签数量
    const MAX_CACHE_PAGE = 3;
    export default {
        components: {
            mediaItem
        },
        data() {
            return {
				isLoading:false,
                newsList: [],
                cacheTab: [],
                tabIndex: 0,
				cityId:null,
				loadMoreDefalutText: '正在加载...',
                tabBars: [{
                    name: '楼盘头条',
                    id: '1',
					page:1,
                }, {
                    name: '吃瓜吐槽',
                    id: '2',
					page:1,
                }, {
                    name: '销售技巧',
                    id: '3',
					page:1
                }, {
                    name: '政策解读',
                    id: '4',
					page:1
                }],
                scrollInto: "",
                showTips: false,
                navigateFlag: false,
                pulling: false,
                refreshIcon: ""
            }
        },
        onLoad() {
			var me=this;
			  this.tabBars.forEach((tabBar) => {
				  this.newsList.push({
					  data: [],
					  isNewsLeft:true,
					  page:1,
					  pid:tabBar.id,
					  isLoading: false,
					  refreshText: "",
					  loadingText: '加载更多...'
				  });
			  });
			 
		    	this.cityId=getApp().globalData.city.id;
			  
			  this.getList(0)
        },
		onShareAppMessage(){
			return {
			      title: '选楼盘，查佣金，看房价'
			    }
		},
        methods: {
            getList(index) {
                let activeTab = this.newsList[index];
               var me = this;
			   me.isLoading=true;
               uni.request({
               	url: me.$rootUrl+'/News/GetList',
               	data: {page:activeTab.page,pageSize:10,pid:activeTab.pid,cityId:me.cityId},
               	method: 'GET',
               	success(res) {
					 me.isLoading=false;
               		if (res.data.success) {
               			 activeTab.data = activeTab.data.concat(res.data.items);
						if (activeTab.data.length >= res.data.total) {
							activeTab.isNewsLeft = false;
							
						} else {
							activeTab.page++;
						}
               		} else {
               			uni.showModal({
               				content: '服务器错误!',
               				showCancel: false
               			});
               		}
               	},
               	fail() {
					 me.isLoading=false;
               		uni.showModal({
               			content: me.connectionFailText,
               			showCancel: false
               		});
               	}
               });
            },
            goDetail(e) {
                if (this.navigateFlag) {
                    return;
                }
                this.navigateFlag = true;
                uni.navigateTo({
                    url: './detail/detail?title=' + e.title
                });
                setTimeout(() => {
                    this.navigateFlag = false;
                }, 200)
            },
            loadMore(e) {
				  let activeTab = this.newsList[this.tabIndex];
				  if(activeTab.isNewsLeft)
				  {
					  setTimeout(() => {
					      this.getList(this.tabIndex);
					  }, 500)
				  }else{
					  uni.showModal({
					  	content: '已经到底了!',
					  	showCancel: false
					  });
				  }
            },
            ontabtap(e) {
                let index = e.target.dataset.current || e.currentTarget.dataset.current;
                this.switchTab(index);
            },
            ontabchange(e) {
                let index = e.target.current || e.detail.current;
                this.switchTab(index);
            },
            switchTab(index) {
                if (this.newsList[index].data.length === 0) {
                    this.getList(index);
                }

                if (this.tabIndex === index) {
                    return;
                }

                // 缓存 tabId
                if (this.newsList[this.tabIndex].data.length > MAX_CACHE_DATA) {
                    let isExist = this.cacheTab.indexOf(this.tabIndex);
                    if (isExist < 0) {
                        this.cacheTab.push(this.tabIndex);
                        //console.log("cache index:: " + this.tabIndex);
                    }
                }

                this.tabIndex = index;
                this.scrollInto = this.tabBars[index].id;

                // 释放 tabId
                if (this.cacheTab.length > MAX_CACHE_PAGE) {
                    let cacheIndex = this.cacheTab[0];
                    this.clearTabData(cacheIndex);
                    this.cacheTab.splice(0, 1);
                    //console.log("remove cache index:: " + cacheIndex);
                }
            },
            clearTabData(e) {
                this.newsList[e].data.length = 0;
                this.newsList[e].loadingText = "加载更多...";
            },
            refreshData() {},
            onrefresh(e) {
                var tab = this.newsList[this.tabIndex];
                if (!tab.refreshFlag) {
                    return;
                }
                tab.refreshing = true;
                tab.refreshText = "正在刷新...";

                setTimeout(() => {
                    this.refreshData();
                    this.pulling = true;
                    tab.refreshing = false;
					tab.refreshFlag = false;
                    tab.refreshText = "已刷新";
                    setTimeout(() => { // TODO fix ios和Android 动画时间相反问题
                        this.pulling = false;
                    }, 500);
                }, 2000);
            },
            onpullingdown(e) {
                var tab = this.newsList[this.tabIndex];
                if (tab.refreshing || this.pulling) {
                    return;
                }
                if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
                    tab.refreshFlag = true;
                    tab.refreshText = "释放立即刷新";
                } else {
                    tab.refreshFlag = false;
                    tab.refreshText = "下拉可以刷新";
                }
            },
            newGuid() {
                let s4 = function() {
                    return (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
                }
                return (s4() + s4() + "-" + s4() + "-4" + s4().substr(0, 3) + "-" + s4() + "-" + s4() + s4() + s4()).toUpperCase();
            },
			loadNewsList() {
				var me = this;
				uni.request({
					url: me.$rootUrl+'/News/GetList',
					data: {page:1,pageSize:6},
					method: 'GET',
					success(res) {
						if (res.data.success) {
							res.data.items.forEach(n => me.newsList.push(n));
						} else {
							uni.showModal({
								content: '服务器错误!',
								showCancel: false
							});
						}
					},
					fail() {
						uni.showModal({
							content: me.connectionFailText,
							showCancel: false
						});
					}
				});
				
			}
			
        }
    }
</script>

<style>
    /* #ifndef APP-PLUS */
    page {
        width: 100%;
        min-height: 100%;
        display: flex;
    }

    /* #endif */

    .tabs {
        flex: 1;
        flex-direction: column;
        overflow: hidden;
        background-color: #ffffff;
        /* #ifdef MP-ALIPAY || MP-BAIDU */
        height: 100vh;
        /* #endif */
    }

    .scroll-h {
        width: 750upx;
        height: 80upx;
        flex-direction: row;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
        /* flex-wrap: nowrap; */
        /* border-color: #cccccc;
		border-bottom-style: solid;
		border-bottom-width: 1px; */
    }

    .line-h {
        height: 1upx;
        background-color: #cccccc;
    }

    .uni-tab-item {
        /* #ifndef APP-PLUS */
        display: inline-block;
        /* #endif */
        flex-wrap: nowrap;
        padding-left: 34upx;
        padding-right: 34upx;
    }

    .uni-tab-item-title {
        color: #555;
        font-size: 30upx;
        height: 80upx;
        line-height: 80upx;
        flex-wrap: nowrap;
        /* #ifndef APP-PLUS */
        white-space: nowrap;
        /* #endif */
    }

    .uni-tab-item-title-active {
        color: #007AFF;
    }

    .swiper-box {
        flex: 1;
    }

    .swiper-item {
        flex: 1;
        flex-direction: row;
    }

    .scroll-v {
        flex: 1;
        /* #ifndef MP-ALIPAY */
        flex-direction: column;
        /* #endif */
        width: 750upx;
		height: 100%;

    }

    .update-tips {
        position: absolute;
        left: 0;
        top: 41px;
        right: 0;
        padding-top: 5px;
        padding-bottom: 5px;
        background-color: #FDDD9B;
        align-items: center;
        justify-content: center;
        text-align: center;
    }

    .update-tips-text {
        font-size: 14px;
        color: #ffffff;
    }

    .refresh {
        width: 750upx;
        height: 64px;
        justify-content: center;
    }

    .refresh-view {
        flex-direction: row;
        flex-wrap: nowrap;
        align-items: center;
        justify-content: center;
    }

	.refresh-icon {
		width: 30px;
		height: 30px;
		transition-duration: .5s;
		transition-property: transform;
		transform: rotate(0deg);
		transform-origin: 15px 15px;
	}

	.refresh-icon-active {
		transform: rotate(180deg);
	}

	.loading-icon {
		width: 20px;
		height: 20px;
		margin-right: 5px;
		color: #999999;
	}

    .loading-text {
        margin-left: 2px;
        font-size: 16px;
        color: #999999;
    }

    .loading-more {
        align-items: center;
        justify-content: center;
        padding-top: 10px;
        padding-bottom: 10px;
        text-align: center;
    }

    .loading-more-text {
        font-size: 28upx;
        color: #999;
    },
	swiper {
		height: 100%;
	
	}

</style>
